import time
import tkinter as tk
from tkinter import ttk, filedialog, scrolledtext
import json
import os
from network.sender import send_file
import queue
from psi.pre_hash import pre_hash

class MainUI:
    def __init__(self, root):
        self.base_dir = os.path.dirname(os.path.abspath(__file__)).replace("\\", "/")+"/../"
        self.root = root
        self.root.title("OT-OPRF Tool")
        self.root.geometry("800x600")
        
        # 创建消息队列用于线程间通信
        self.message_queue = queue.Queue()
        
        # 创建主框架
        self.main_frame = ttk.Frame(self.root, padding="10")
        self.main_frame.grid(row=0, column=0, sticky = (tk.W, tk.E, tk.N, tk.S))

        # IP输入区域
        ttk.Label(self.main_frame, text="IP地址:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.ip_var = tk.StringVar()
        self.ip_entry = ttk.Entry(self.main_frame, textvariable=self.ip_var, width=40)
        self.ip_entry.grid(row=0, column=1, sticky=tk.W, pady=5)
        
        # 添加保存IP按钮
        self.save_ip_button = ttk.Button(self.main_frame, text="保存IP", command=self.save_ip_directly)
        self.save_ip_button.grid(row=0, column=2, padx=5, pady=5)

        # 文件选择区域
        ttk.Label(self.main_frame, text="选择文件:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.file_path_var = tk.StringVar()
        self.file_entry = ttk.Entry(self.main_frame, textvariable=self.file_path_var, width=40)
        self.file_entry.grid(row=1, column=1, sticky=tk.W, pady=5)
        self.browse_button = ttk.Button(self.main_frame, text="浏览", command=self.browse_file)
        self.browse_button.grid(row=1, column=2, padx=5, pady=5)

        # 执行按钮
        self.execute_button = ttk.Button(self.main_frame, text="执行", command=self.execute_function)
        self.execute_button.grid(row=2, column=1, pady=10)

        # 日志显示区域
        ttk.Label(self.main_frame, text="执行日志:").grid(row=3, column=0, sticky=tk.W, pady=5)
        self.log_text = scrolledtext.ScrolledText(self.main_frame, width=110, height=30)
        self.log_text.grid(row=4, column=0, columnspan=3, pady=5)
        
        # 加载保存的IP
        self.load_saved_ip()
        
    def browse_file(self):
        filename = filedialog.askopenfilename(
            title="选择文件",
            filetypes=(("所有文件", "*.*"),)
        )
        if filename:
            self.file_path_var.set(filename)
            self.log_message(f"已选择文件: {filename}")
    
    def execute_function(self):
        ip = self.ip_var.get()
        file_path = self.file_path_var.get()
        
        if not ip:
            self.log_message("错误: 请输入IP地址")
            return
        
        if not file_path:
            self.log_message("错误: 请选择文件")
            return
        
        # 保存IP到配置文件
        self.save_ip(ip)
        
        # 这里添加执行功能的代码
        self.log_message(f"开始执行...")
        self.log_message(f"client:预处理文件: {file_path}")
        start = time.time()
        pre_hash(file_path,"a")
        self.log_message(f"client:预处理完成")
        cost = (time.time() - start)*1000
        self.log_message(f"client:预处理耗时: {cost:.2f}ms")
        self.log_message(f"client:正在请求连接...")
        send_file(filename="request",mode="cmd")
    
    def log_message(self, message):
        # 将消息放入队列
        self.message_queue.put(message)
        # 直接在主线程中处理消息
        self.root.after_idle(self._process_messages)
    
    def _process_messages(self):
        """处理消息队列中的消息"""
        try:
            while True:
                message = self.message_queue.get_nowait()
                self.log_text.insert(tk.END, message + "\n")
                self.log_text.see(tk.END)
        except queue.Empty:
            pass
    
    def save_ip_directly(self):
        ip = self.ip_var.get()
        if not ip:
            self.log_message("错误: 请输入IP地址")
            return
        self.save_ip(ip)
        self.log_message(f"IP地址已保存: {ip}")
    
    def save_ip(self, ip):
        try:
            # 先读取现有配置
            config = {}
            if os.path.exists(self.base_dir+"conf/config.json"):
                with open(self.base_dir+"conf/config.json", "r") as f:
                    config = json.load(f)
            # 更新IP
            config["ip"] = ip
            # 写入更新后的配置
            with open(self.base_dir+"conf/config.json", "w") as f:
                json.dump(config, f)
        except Exception as e:
            self.log_message(f"保存IP失败: {str(e)}")
    
    def load_saved_ip(self):
        try:
            if os.path.exists(self.base_dir+"conf/config.json"):
                with open(self.base_dir+"conf/config.json", "r") as f:
                    config = json.load(f)
                    if "ip" in config:
                        self.ip_var.set(config["ip"])
        except Exception as e:
            self.log_message(f"加载配置文件失败: {str(e)}")

# 全局变量用于存储UI实例
root = tk.Tk()
ui_instance = MainUI(root)

def start_ui():
    root.mainloop()


if __name__ == "__main__":
    start_ui()
